#! /bin/sh
# This script is a generic wrapper for iotk.x
#
# if the first option is --iotk-exe,
#   then the second option is assumed to be the iotk.x executable and all the remaining options are passed.
# else, if the IOTK_EXE environment variable is defined,
#   then the iotk.x command will be executed as ${IOTK_EXE} .
# else, if the IOTK_ROOTDIR environment variable is defined,
#   then the iotk.x command will be executed as ${IOTK_ROOTDIR}/bin/iotk.x .
# else, the execution path is searched for an executable "iotk.x"
#   then the iotk.x command will be executed as iotk.x
# else, the directory is guessed based on the location of THIS ($0) script
#   then the iotk.x command will be executed properly
# else, an error message is issued
# end if

# When a single instance of iotk library is available on a given machine,
# the user should define an environment variable IOTK_ROOTDIR as
# the name of the root directory of iotk, e.g.
#   export IOTK_ROOTDIR=${HOME}/S3DE/iotk/

# When different istances of iotk are available on the same machine
# (e.g. different versions or different compilers), the user can define aliases as:
#   alias iotk_g95 "iotk --iotk-exe ${HOME}/g95/S3DE/iotk/bin/iotk.x"
#   alias iotk_ifort "iotk --iotk-exe ${HOME}/ifort/S3DE/iotk/bin/iotk.x"

EXEC=
# first, check --iotk-exe command line option
if test "$1" = --iotk-exe
then
  shift
  EXEC="$1"
  shift
# second, try IOTK_EXE environment variable
elif test -n "${IOTK_EXE}"
then
  EXEC="${IOTK_EXE}"
# third, try IOTK_ROOTDIR environment variable
elif test -n "${IOTK_ROOTDIR}"
then
  EXEC="${IOTK_ROOTDIR}/bin/iotk.x"
else
# fourth, try to execute using the path
  echo "--do-nothing" | iotk.x 2> /dev/null
  if [ $? = 0 ]
  then
    EXEC=iotk.x
# last resort, guess using $0
# (thanks to Andrea Ferretti)
  else
    EXEC=`echo $0 | sed 's/\(.*\)\/.*/\1/'`/../bin/iotk.x
    echo "--do-nothing" | ${EXEC} 2> /dev/null
    if [ $? = 0 ]
    then
      echo "iotk: using ${EXEC} executable" 1>&2
    else
# very last: surrend
      echo "iotk: I cannot find the iotk.x executable" 1>&2
      echo "iotk: try $0 --iotk-exe EXE" 1>&2
      echo "iotk: where EXE is the complete path to the iotk.x executable" 1>&2
      exit 1
    fi
  fi
fi

# transfer of command-line arguments to standard input
# a pipe (|) is added at the end of each line to recognize line end,
# allowing for single items explicitily ending with one or more spaces
# the pipe is then removed inside the iotk.x parser.
for argument
do
  echo "$argument|"
done | ${EXEC}
